package ysq.xyg.recovery.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.recovery.dao.RecoverySackMemberDao;
import ysq.xyg.recovery.model.po.RecoveryOrder;
import ysq.xyg.recovery.model.po.RecoverySack;
import ysq.xyg.recovery.model.po.RecoverySackMember;
import ysq.xyg.recovery.model.po.RecoverySackRecord;
import ysq.xyg.recovery.model.vo.RecoverySackMemberVo;
import ysq.xyg.recovery.model.vo.RecoverySackVo;
import ysq.xyg.recovery.service.RecoveryOrderService;
import ysq.xyg.recovery.service.RecoverySackMemberService;
import ysq.xyg.recovery.service.RecoverySackRecordService;
import ysq.xyg.recovery.service.RecoverySackService;
import ysq.xyg.shop.service.ShopAddressService;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.service.WebMemberService;

import java.util.Date;
import java.util.List;

/**
 * 回收金模块-袋子绑定用户service实现
 *
 * @author congcong
 * @date 2019-7-8 14:46:16
 */
@Service("recoverySackMemberService")
public class RecoverySackMemberServiceImpl extends BaseServiceImpl<RecoverySackMember> implements RecoverySackMemberService {

    @Autowired
    private RecoveryOrderService recoveryOrderService;
    @Autowired
    private RecoverySackService recoverySackService;
    @Autowired
    private RecoverySackRecordService recoverySackRecordService;
    @Autowired
    private RecoverySackMemberDao recoverySackMemberDao;
    @Autowired
    public void setBaseDao(RecoverySackMemberDao recoverySackMemberDao) {
        this.baseDao = recoverySackMemberDao;
    }

    private RecoverySackMember recoverySackMember;

    /**
     * 分页查询
     *
     * @param recoverySackMemberVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong
     * @date 2019-7-8 14:46:16
     */
    @Override
    public ReturnEntity page(RecoverySackMemberVo recoverySackMemberVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<RecoverySackMember> list = acceptList(recoverySackMemberVo);
        PageInfo<RecoverySackMember> page=new PageInfo<RecoverySackMember>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(RecoverySackMemberVo recoverySackMemberVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        if (StringUtils.isNotEmpty(recoverySackMemberVo.getMemberNickName())) {
            recoverySackMemberVo.setMemberNickName(BaseUtil.encodeBase64String(recoverySackMemberVo.getMemberNickName()));
        }
        List<RecoverySackMember> list = recoverySackMemberDao.selectEntityList(recoverySackMemberVo);
        if (list != null && list.size() > 0) {
            for (RecoverySackMember recoverySackMember : list) {
                if (StringUtils.isNotEmpty(recoverySackMember.getMemberNickName())) {
                    recoverySackMember.setMemberNickName(BaseUtil.decodeBase64(recoverySackMember.getMemberNickName()));
                }
                if (recoverySackMember.getCreateTime() != null) {
                    recoverySackMember.setCreateTimeStr(DateUtil.formatDateTime(recoverySackMember.getCreateTime()));
                }
            }
        }
        PageInfo<RecoverySackMember> page = new PageInfo<RecoverySackMember>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param recoverySackMemberVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong
     * @date 2019-7-8 14:46:16
     */
    @Override
    public ReturnEntity addOrUpdate(RecoverySackMemberVo recoverySackMemberVo, SysUser currentUser) {
        boolean isUpate = true;
        if (StrUtil.isEmpty(recoverySackMemberVo.getId())) {
            recoverySackMember = new RecoverySackMember(currentUser);
            isUpate=false;
        } else {
            recoverySackMember=selectByPrimaryKey(recoverySackMemberVo.getId());
            if(ObjectUtil.isNull(recoverySackMember)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoverySackMember.setUpdateTime(new Date());
            recoverySackMember.setUpdateUser(currentUser.getId());
        }
        recoverySackMember.setMemberId(recoverySackMemberVo.getMemberId());
        recoverySackMember.setSackId(recoverySackMemberVo.getSackId());
        recoverySackMember.setStatus(recoverySackMemberVo.getStatus());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(recoverySackMember);
        }else{
            num=insert(recoverySackMember);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong
     * @date 2019-7-8 14:46:16
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        RecoverySackMember recoverySackMember=selectByPrimaryKey(id);
        if(recoverySackMember!=null){
            recoverySackMember.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            recoverySackMember.setUpdateTime(new Date());
            recoverySackMember.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(recoverySackMember);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param recoverySackMemberVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong
     * @date 2019-7-8 14:46:16
     */
    @Override
    public List<RecoverySackMember> acceptList(RecoverySackMemberVo recoverySackMemberVo){
        Example example = new Example(RecoverySackMember.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(recoverySackMemberVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",recoverySackMemberVo.getRemoveTag());
        }
        example.setOrderByClause(" update_time desc");
        return recoverySackMemberDao.selectByExample(example);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity coverSack(String id, String memberPhone, String memberAddress) {
        // 预约会生成记录，现有id
        RecoverySackMember recoverySackMember = this.selectByPrimaryKey(id);
        String sackId = recoverySackMember.getSackId();
        RecoverySack recoverySack = recoverySackService.selectByPrimaryKey(sackId);
        String memberId = recoverySackMember.getMemberId();
        RecoverySackRecord recoveryRecord = new RecoverySackRecord();
        recoveryRecord.setId(BaseUtil.uId());
        recoveryRecord.setSackMemberId(id);
        recoveryRecord.setMemberId(memberId);
        if (recoverySack != null) {
            recoveryRecord.setStackNum(recoverySack.getCardNo());
        }
        recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoveryRecord.setCreateTime(DateUtil.date());
        recoveryRecord.setUpdateTime(DateUtil.date());
        recoveryRecord.setStatus(BaseConstant.RECOVERY_RECORD_STATUS_ONE);
        recoveryRecord.setMemberPhone(memberPhone);
        recoveryRecord.setMemberAddress(memberAddress);
        int info = recoverySackRecordService.insert(recoveryRecord);
        if (info <= 0) {
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity bindSack(String memberId, String cardNo) {
        // 查看是否购买，如果购买才能绑定
        // 查询是否已存在订单
        RecoveryOrder orderSearch = new RecoveryOrder();
        orderSearch.setMemberId(memberId);
        List<RecoveryOrder> recoveryOrderList = recoveryOrderService.select(orderSearch);
        if (recoveryOrderList == null || recoveryOrderList.size() == 0) {
            return new ReturnEntity(BaseConstant.FAIL, "未查询到购买记录");
        }
        int num = 0;
        for (RecoveryOrder recoveryOrder : recoveryOrderList) {
            num = num + recoveryOrder.getNum();
        }
        // 正在使用的袋子
        RecoverySackMember recoverySackMemberVo = new RecoverySackMember();
        recoverySackMemberVo.setMemberId(memberId);
        recoverySackMemberVo.setStatus(BaseConstant.RECOVERY_SACK_MEMBER_STATUS_USEING);
        int memberNum = this.selectCount(recoverySackMemberVo);
        if (memberNum > num) {
            return new ReturnEntity(BaseConstant.FAIL, "未查询到购买记录");
        }

        // 绑定袋子，查看袋子情况
        RecoverySackVo recoverySackVo = new RecoverySackVo();
        recoverySackVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoverySackVo.setCardNo(cardNo);
        recoverySackVo.setStatus(BaseConstant.RECOVERY_SACK_STATUS_UNUSED);
        List<RecoverySack> recoverySacks = recoverySackService.acceptList(recoverySackVo);
        if (recoverySacks == null || recoverySacks.size() == 0) {
            return new ReturnEntity(BaseConstant.FAIL, "未查询到未使用的袋子");
        }
        RecoverySack recoverySack = recoverySacks.get(0);
        if (StringUtils.equals(recoverySack.getStatus(), BaseConstant.RECOVERY_SACK_STATUS_USED)) {
            return new ReturnEntity(BaseConstant.FAIL, "袋子已使用");
        }
        // 袋子已使用
        recoverySack.setStatus(BaseConstant.RECOVERY_SACK_STATUS_USED);
        recoverySackService.updateByPrimaryKeySelective(recoverySack);
        // 生成recoveryMember数据
        RecoverySackMember recoverySackMember = new RecoverySackMember();
        recoverySackMember.setId(BaseUtil.uId());
        recoverySackMember.setMemberId(memberId);
        recoverySackMember.setSackId(recoverySack.getId());
        // 绑定后即在使用中
        recoverySackMember.setStatus(BaseConstant.RECOVERY_SACK_MEMBER_STATUS_USEING);
        recoverySackMember.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoverySackMember.setCreateTime(DateUtil.date());
        recoverySackMember.setUpdateTime(DateUtil.date());
        this.insert(recoverySackMember);
        return new ReturnEntity();
    }
}
